package com.tianji.remark.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tianji.api.dto.remark.LikedTimesDTO;
import com.tianji.common.autoconfigure.mq.RabbitMqHelper;
import com.tianji.common.utils.StringUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.remark.domain.dto.LikeRecordFormDTO;
import com.tianji.remark.domain.po.LikedRecord;
import com.tianji.remark.mapper.LikedRecordMapper;
import com.tianji.remark.service.ILikedRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.tianji.common.constants.MqConstants.Exchange.LIKE_RECORD_EXCHANGE;
import static com.tianji.common.constants.MqConstants.Key.LIKED_TIMES_KEY_TEMPLATE;

/**
 * <p>
 * 点赞记录表 服务实现类
 * </p>
 *
 * @author xioayang
 * @since 2024-06-28
 */
//@Service
@RequiredArgsConstructor
public class LikedRecordServiceImpl extends ServiceImpl<LikedRecordMapper, LikedRecord> implements ILikedRecordService {

    private final RabbitMqHelper mqHelper;
    /**
     * 点赞或取消点赞
     *
     * @param recordDTO 点赞业务类型
     */
    @Override
    public void addLikeRecord(LikeRecordFormDTO recordDTO) {
        // 判断是否点赞,
        Boolean isliked = recordDTO.getLiked() ? like(recordDTO) : unLike(recordDTO);
        //判断执行是否成功
        if (!isliked){
            return;
        }
        //统计点赞数
        Integer likedTimes  = lambdaQuery().eq(LikedRecord::getBizId, recordDTO.getBizId())
                .count();
        //MQ发送消息通知业务方
        mqHelper.send(
                LIKE_RECORD_EXCHANGE,
                StringUtils.format(LIKED_TIMES_KEY_TEMPLATE,recordDTO.getBizType()),
                LikedTimesDTO.of(recordDTO.getBizId(),likedTimes));


    }

    /**
     * 批量查询点赞状态
     *
     * @param bizIds 点赞业务id
     * @return 点赞状态
     */
    @Override
    public Set<Long> isBizLiked(List<Long> bizIds) {
        //查询点赞状态
        List<LikedRecord> records = lambdaQuery()
                .eq(LikedRecord::getUserId, UserContext.getUser())
                .in(LikedRecord::getBizId, bizIds)
                .list();
        //转成set返回
        return records.stream().map(LikedRecord::getBizId).collect(Collectors.toSet());
    }

    /**
     * 读取点赞次数并发送消息
     *
     * @param bizType    业务类型
     * @param maxBizSize 最大业务数量
     */
    @Override
    public void readLikeTimesAndSendMessage(String bizType, Integer maxBizSize) {

    }

    /**
     * 取消点赞
     * @param recordDTO 点赞业务类型
     * @return 是否取消点赞
     */
    private Boolean unLike(LikeRecordFormDTO recordDTO) {
        // 不是点赞，删除点赞记录，
        return remove(new QueryWrapper<LikedRecord>().lambda()
                .eq(LikedRecord::getBizId, recordDTO.getBizId())
                .eq(LikedRecord::getUserId, UserContext.getUser())

        );
    }

    /**
     * 执行点赞
     * @param recordDTO 点赞业务类型
     * @return 是否取消点赞
     */
    private Boolean like(LikeRecordFormDTO recordDTO) {
        // 是点赞，判断是否点过赞，是，直接返回，不是新增点赞记录
        //查询记录
        //获得userId
        Long userId = UserContext.getUser();
        Integer count = lambdaQuery()
                .eq(LikedRecord::getBizId, recordDTO.getBizId())
                .eq(LikedRecord::getUserId, UserContext.getUser())
                .count();
        //判断该userId是否存在
        //存在直接结束
        if (count>0) {
            return false;
        }
        //不存在就新增
        save(new LikedRecord()
                .setBizId(recordDTO.getBizId())
                .setUserId(userId)
                .setBizType(recordDTO.getBizType()));
        return true;
    }
}
